package com.fingard.dsp.bank.directbank.fuiou01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.FtpUtil;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class FUIOU01Transaction extends FUIOU01Base implements ITransaction {


    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        //retAts.writeStart();
        //获取充值对账单
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String[] rechargeRespHeader = getRechargeTransaction(p_req7516, retAts);
        //获取代付对账单
        String[] tmpPayRespHeader = getPayTransaction(p_req7516, retAts);
        if (rechargeRespHeader[0].equals("-1")&&tmpPayRespHeader[0].equals("-1")) {
            String respInfo = rechargeRespHeader[1];
            if (StringHelper.isNullOrEmpty(respInfo)) {
                respInfo = tmpPayRespHeader[1];
            }
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(respInfo);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = rechargeRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = tmpPayRespHeader[1];
                }
                if (StringHelper.isNullOrEmpty(rechargeRespHeader[1])) {
                    respInfo=rechargeRespHeader[1];
                }
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            }
        }
        retAts.writeEnd();
        return retAts;
    }


    private String[] getRechargeTransaction(Req7516HisTrans p_req7516, RetAtsTrans retAts) throws Exception {
        //RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String[] respHeader = new String[]{"", ""};
        String respCode = "";
        String respInfo = "";

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            //按日循环查询
            FtpSet ftpSet = bankFront.getFtpSet("transaction");
            ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "Transaction");
            while (tmpIntFrom <= tmpIntTo&&StringHelper.isNullOrEmpty(respCode)) {
                String ftpFileContent = "";
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                if (actItem != null) {
                    // FTP服务器配置信息
                    String ftpHost = getBankConfig().getMapValueByKey("ftpMapping", "ftpHost");
                    int ftpPort = Integer.parseInt(getBankConfig().getMapValueByKey("ftpMapping", "ftpPort"));

                    // FTP登录用户信息
                    String ftpUserName = getBankConfig().getMapValueByKey("ftpMapping", "ftpUserName");
                    String ftpPassword = getBankConfig().getMapValueByKey("ftpMapping", "ftpPassword");

                    // 对账单文件所在目录
                    String ftpPath = getBankConfig().getMapValueByKey("ftpMapping", "ftpRechargePath");
                    ftpPath = ftpPath  + "/"+ Format.Date8Format.format(tmpCalendarFrom.getTime()) + "/";

                    // 本地路径
                    String localPath = getBankConfig().getMapValueByKey("ftpMapping", "localPath");
                    String fileName = Format.Date8Format.format(tmpCalendarFrom.getTime()) + "_" + actItem.merchantId + "_" + "recharge.txt";
                    // 从FTP下载对账单
                    //FtpReceiver ftpReceiver= sftpPortClient.uploadFile("", fullFilePath, fileName);
                    String posRecRequestType = getBankConfig().getValueAsString("requestType");
                    if ("ftp".equals(posRecRequestType.toLowerCase())) {
                        FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
                        String filePath1 = StringHelper.trimEnd(localPath, "/")+ File.separator + fileName;
                        ftpFileContent = FtpUtil.getTextFromFile(filePath1, "GBK");
                    } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                        localPath = StringHelper.trimEnd(localPath, "/") + File.separator + fileName;
                        ftpPath=ftpPath+fileName;
                        WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + ftpPath);
                        FtpReceiver ftpReceiver = sftpPortClient.downloadFile("/recharge",ftpPath, localPath);
                        if (ftpReceiver.isCompleted) {
                            if (ftpFileContent.length() > 0) {
                                ftpFileContent=ftpFileContent+"\n";
                            }
                            ftpFileContent=FileHelper.readFileText(localPath, "GBK");
                        } else {
                            respCode = "-1";
                            respInfo = "对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                            break;
                        }
                    }
                    //SftpPortClient
                    // 从本地文件读取对账单数据
                    if (ftpFileContent.equals("")) {

                    }else {
                        // 返回对账单文件数据
                        WriteBankLogStep3(ftpFileContent);
                        // 解析富友对账单
                        String[] totalLine = ftpFileContent.split("\r\n");
                        if (totalLine.length > 0) {
                            respInfo = "";
                            String tmpStrRet = ftpFileContent.toString();
                            WriteBankLogLn2("充值对账单响应数据:\r\n" + tmpStrRet);
                            StringReader strReader = new StringReader(tmpStrRet);
                            BufferedReader reader = new BufferedReader(strReader);
                            //0业务代码|1交易日期|2交易流水|3记账日期|4记账流水|5交易金额(单位:分)
                            String readLine = "";
                            //InputStreamReader isr = new InputStreamReader(new FileInputStream(dealedPath), getCharset());
                            // BufferedReader reader = new BufferedReader(isr);
                            while ((readLine = reader.readLine()) != null) {
                                // 每行明细内容
                                String[] transDetail = readLine.split("\\|");
                                if (transDetail.length > 5) {
                                    // RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
                                    RetAtsTransDetail retDetail = new RetAtsTransDetail();
                                    //业务代码
                                    retDetail.busType = transDetail[0].trim();
                                    //交易日期
                                    retDetail.tranDate = transDetail[1].trim();
                                    retDetail.valueDate = retDetail.tranDate;
                                    //交易金额
                                    retDetail.tranAmt = StringHelper.amountDivide100(transDetail[5].trim());
                                    //交易流水
                                    retDetail.askNumber = transDetail[2].trim();
//                                    if (mapKV.containsKey("记账日期")) {
//                                        retDetail.postingDate = mapKV.get("记账日期").trim() + "000000";
//                                   }
                                    retDetail.cdFlag = "1";
                                    retAts.writeRetDetailWithoutRespCode(retDetail);
                                }
                            }
                        }
                    }
                } else {
                    respHeader[0] = "-1";
                    respHeader[1] = "未找到账号[" + p_req7516.actNum + "]商户配置信息";
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        respHeader[0] = respCode;
        respHeader[1] = respInfo;
        return respHeader;
    }

    private String[] getPayTransaction(Req7516HisTrans p_req7516, RetAtsTrans retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};
        String respCode = "";
        String respInfo = "";
        try {
            FtpSet ftpSet = bankFront.getFtpSet("transaction");
            ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "Transaction");
            if (actItem != null&&ftpSet!=null) {
                Calendar tmpCalendarFrom = Calendar.getInstance();
                tmpCalendarFrom.setTime(p_req7516.getDateFrom());
                Calendar tmpCalendarTo = Calendar.getInstance();
                tmpCalendarTo.setTime(p_req7516.getDateTo());
                int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                //按天循环查询
                while (tmpIntFrom <= tmpIntTo&&StringHelper.isNullOrEmpty(respCode)) {
                    String ftpFileContent = "";
                    Date fromDateStep = tmpCalendarFrom.getTime();
                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    // FTP服务器配置信息
                    String ftpHost = getBankConfig().getMapValueByKey("ftpMapping", "ftpHost");
                    int ftpPort = Integer.parseInt(getBankConfig().getMapValueByKey("ftpMapping", "ftpPort"));

                    // FTP登录用户信息
                    String ftpUserName = getBankConfig().getMapValueByKey("ftpMapping", "ftpUserName");
                    String ftpPassword = getBankConfig().getMapValueByKey("ftpMapping", "ftpPassword");

                    // 对账单文件所在目录
                    String ftpPath = getBankConfig().getMapValueByKey("ftpMapping", "ftpPayPath");
                    ftpPath = ftpPath + "/"+ Format.Date8Format.format(tmpCalendarFrom.getTime()) + "/";

                    // 本地路径
                    String localPath = getBankConfig().getMapValueByKey("ftpMapping", "localPath");
                    String fileName = actItem.merchantId + "_" + Format.Date8Format.format(tmpCalendarFrom.getTime()) + ".txt";
                    // 从FTP下载对账单
                    //FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
                    String posRecRequestType = getBankConfig().getValueAsString("requestType");
                    if ("ftp".equals(posRecRequestType.toLowerCase())) {
                        FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
                        String filePath1 = localPath + File.separator + fileName;
                        ftpFileContent = FtpUtil.getTextFromFile(filePath1, "GBK");
                    } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                        localPath = localPath + File.separator + fileName;
                        ftpPath=ftpPath+fileName;
                        WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + ftpPath);
                        FtpReceiver ftpReceiver = sftpPortClient.downloadFile("/account",ftpPath, localPath);
                        if (ftpReceiver.isCompleted) {
                            if (ftpFileContent.length() > 0) {
                                ftpFileContent=ftpFileContent+"\n";
                            }
                            ftpFileContent=FileHelper.readFileText(localPath, "GBK");
                        } else {
                            respCode = "-1";
                            respInfo = "对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                            break;
                        }
                    }
                    // 从本地文件读取对账单数据
                    //String filePath2 = localPath + File.separator + fileName;
                    //String ftpFileContent = FtpUtil.getTextFromFile(filePath2, "GBK");
                    if (ftpFileContent.equals("")) {
                        //当前日期没有对账单数据
                    }else {
                        // ftpFileContent = new String(ftpFileContent.getBytes("gbk"),"utf-8");
                        WriteBankLogStep3(ftpFileContent);
                        // 解析富友对账单
                        //0业务代码|1交易来源|2交易流水号|3源交易流水号|4富友帐务流水号|5文件明细号|6交易提交时间|7商户复核时间|8交易发送时间|
                        // 9交易类型|10文件名|11交易金额|12交易手续费|13户名|14扣款账号|15卡属性|16发卡机构|17收款账号|18注释|19企业流水号|20备注|21手机号
                        String[] totalLine = ftpFileContent.split("\r\n");
                        if (totalLine.length > 0) {
                            for (int i = 0; i < totalLine.length; i++) {
                                RetAtsTransDetail retDetail = new RetAtsTransDetail();
                                String[] values = totalLine[i].split("\\|");
                                //交易提交时间
                                if (values.length > 20){
                                    if (StringHelper.hasAnyChar(values[6])) {
                                        retDetail.tranTime = values[6];
                                        retDetail.tranDate = values[6].substring(0,10);
                                        retDetail.valueDate = retDetail.tranDate;//mapKV.get("交易日期").trim();
                                    }
                                    if (StringHelper.hasAnyChar(values[20])) {
                                        retDetail.comment = values[20];
                                        retDetail.usage = values[20];
                                        retDetail.abstr = pickupAbstr(values[20]);
                                    }
                                    retDetail.recAccNum = values[17];
                                    retDetail.recAccName = values[13];
                                    //支付码应该对应哪个retDetail.payCode = ;
                                    retDetail.askNumber = values[19];//交易流水号
                                    retDetail.receiptNo=values[19];
                                    retDetail.busRef=values[19];
                                    //账户余额没有retDetail.accBal
                                    if (StringHelper.hasAnyChar(values[3])) {
                                        if (StringHelper.hasAnyChar(values[11])) {
                                            retDetail.tranAmt = StringHelper.amountDivide100(values[11]);
                                        }
                                    } else {
                                        if (StringHelper.hasAnyChar(values[11])) {
                                            retDetail.tranAmt = "-" + StringHelper.amountDivide100(values[11]);
                                        }
                                    }
                                    if (StringHelper.hasAnyChar(values[9])) {
                                        retDetail.busType = values[9];
                                    }
                                    retAts.writeRetDetailWithoutRespCode(retDetail);
                                }
                            }
                        }
                    }
                    // 返回对账单文件数据
                }
            }else {
                respHeader[0] = "-1";
                respHeader[1] = "未找到账号[" + p_req7516.actNum + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        respHeader[0] = respCode;
        respHeader[1] = respInfo;
        return respHeader;
    }



    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;//设置开始时间和结束时间都为当天
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}

